package org.pi.common.plot.figures

import org.pi.common.matrix.FloatMatrix
import org.pi.common.plot.axes.ImageAxes
import org.pi.common.matrix.Api._
import org.pi.common.vision.Api._

trait FiguresApi {
	private val figures = new scala.collection.mutable.HashMap[Int,Figure]
	private var gcfValue : Figure = null
	
	def gcf = {
	  if (gcfValue==null) figure
	  gcfValue
	}
	def gcf_=(f: Figure) = {
		gcfValue = f
	}
	def gca = {
		if (gcf==null) figure
		gcf.getCurrentAxes
	}
	
	def figure() : Figure = {
		var index = 0
		while(figures.contains(index)) index+=1
		figure(index)
	}
	
	def subplot(x: Int, y:Int, index: Int) = gcf.subplot(x,y,index)

	def figure(index: Int) : Figure = {
		if (figures.contains(index)) {
			gcfValue = figures(index)
			gcfValue.activate
			gcfValue
		}
		else {
			gcfValue = SwingFigure.figure
			figures(index) = gcfValue
			gcfValue.activate
			gcfValue
		}
	}

	def plot(y: FloatMatrix, params: Any*) : Unit = {
		val x = linspace(0.0f,(y.length-1).toFloat,y.length)
		plot(x,y,params:_*)
	}
	
	def plot(x: FloatMatrix, y: FloatMatrix, params: Any*): Unit = {
	  import org.pi.common.reflect.Api._
	  //gca.addDrawable( new org.pi.common.plot.drawables.Line(0,0,10,10) )
	  if (x.length != y.length) throw new Error("x and ymust have the same size!")
	  val pts = new Array[org.pi.common.geom.Point](x.length)
	  var k: Int  = 0
	  while (k < x.length) {
	 	  pts(k) = org.pi.common.geom.Point( x(k),y(k) )
	 	  k += 1
	  }
	  val obj = new org.pi.common.plot.drawables.Function(pts.toList)
	  gca.addDrawable( obj )
	  if (params.length>0) set(obj,params:_*)
	  obj
	}
	
	def imshow(image: FloatMatrix) : Unit = {
		gcf.setCurrentAxes( new ImageAxes(image) )
	}
}

object Api extends FiguresApi {
  def main(args: Array[String]) {
    println("START")

    subplot(2,2,0)
    imshow(rgb2gray(imread("data/blume2.png")))
    plot( 1.0f::100.0f::170.0f::200.0f::Nil, 50.0f::100.0f::20.0f::160.0f::Nil )
	
    subplot(2,2,1)
    val t = linspace(0,2*pi,100)
    val y1 = sin(t)
    val y2 = cos(t*2)*1.5f //cos
    plot( t, y1)
    plot( t, y2, "lineWidth", 0.5f, "color", java.awt.Color.red )

    subplot(2,2,2)
    imshow(rand(200,320,3))
    
    subplot(2,2,3)
    imshow(rand(200,320))
    
    gcf.saveAs("figure.png")
	
	println("END")
  }
}

